/*
 *	project-view view
 *  -----------------------------------------------------------------------------------------------------------
 */

site.view('project-view', {
	
	route: '/project/edit/:id',
	parent: 'desktop-view',
	projectViewHtml: null,
	elementId: 'project',
	
	onLoad: function(settings) {
		
		var that = this;

		this.request({
			url: '/project/show',
			type: 'post',
			dataType: 'json',
			data: settings,
			success: function(data) {
				that.projectViewHtml = that.createElement('div');
				that.projectViewHtml.setAttribute('id', that.elementId);
				that.projectViewHtml.setAttribute('style', 'display: none;');	
				that.projectViewHtml.innerHTML = data.content;
				
				var o = util.extend({view: that.projectViewHtml}, settings);
				that.startAll(o);
				that.trigger('showProject', that.projectViewHtml);
			}
		});
	},
	
	onUnload: function() {
		this.trigger('hideProject');
		this.projectViewHtml = null;
		this.stopAll();
	}

})

.module('project_manager', function(context) {
	
	var container,
		licence,
	
	actCloseProject = function() {
		context.setView('desktop-view');
		return false;
	};

	context.require('fixedProjectHeader').init();

	return {
		
		init: function(settings) {
			container = context.query(settings.view);
			licence = context.query('#licence');
			

			context.query('body').append(settings.view);
			container.delegate('a.button_close', 'click', actCloseProject);
	
		},
		
		destroy: function() {
			container.undelegate('a.button_close', 'click', actCloseProject);
		},
		
		events: {
			showProject: function(htmlView) {
				container.show();
			},
			
			hideProject: function() {
				container.hide();
				container.html('');
				container.remove();
			}
		}
	}
	
})

.module('project_tags', function(context) {
	var query = context.query,
		request = context.request,
		require = context.require,
		notify = require('notify'),
		textBoxList = context.require('TextboxList'),
		
		tagsList,
		tags,
		currentTags = '';

	return {
		init: function(settings) {

			tags = context.query('#tags');
			currentTags = tags.val();

			// in next tick because of not filled width property of tags
			setTimeout(function(){
				tagsList = textBoxList.create('#tags', {
		         	unique: true,
		         	plugins: {
			         	autocomplete: {
							minLength: 3,
							queryRemote: true,
							remote: {url: '/project/get_tags'}
						}
					}
				});

				function updateTags(){

					if(currentTags !== tags.val()) {
						// update tags
						
						currentTags = tags.val();
						
						var request_data = {
							id: settings.id,
							tags: currentTags
						}

						request({		
							url: '/project/update_tags',
							dataType: 'json',
							type: "post",
							data: request_data,

							error: function(err) {
								notify.create('create','error-template', {
									title: 'Error',
									text: 'Project tags cannot be updated. Service unavailable.'
								});
							}
						});
					}
				}


				tagsList.addEvent('bitAdd', updateTags);
				tagsList.addEvent('bitRemove', updateTags);
			}, 0);

		},

		destroy: function() {
			tags.undelegate('change');
		}
	}
})

.module('project_licence', function(context) {
	var query = context.query,
		request = context.request,
		require = context.require,
		notify = require('notify'),

		licence;

	return {
		init: function(settings) {
			
			licence = query('#licence');

			licence.bind('change', function() {
				
				var request_data = {
					id: settings.id,
					licence: licence.val()
				}
					
				request({	
						
					url: '/project/update_licence',
					dataType: 'json',
					type: "post",
					data: request_data,

					error: function(err) {

						notify.create('create','error-template', {
							title: 'Error',
							text: 'Project licence cannot be updated. Service unavailable.'
						});
					}
				});
			});
		},

		destroy: function() {
			licence.unbind('change');
		}
	}

})

.module('project_content_list', function(context) {
	var query = context.query,
		container;

	return {
		init: function(settings) {
			container = query('.project_list', '#project_content');
		},

		events: {
			addProjectElement: function(element) {
				var el = query(element).hide();
				container.append(el);
				el.slideDown(function() {
					
					$('html, body').animate({ 
	   					scrollTop: $(document).height()-$(window).height()}, 
	   					500
					);

				});	
			}
		}
	}
})

.module('project_editing_tabs', function(context) {
	
	var container,
		query = context.query,
		TabControl = context.require('Tabs').TabControl;
	
		containersEditTab = new TabControl();

	return {
		
		init: function(settings) {
			
			// Build editing containers tabs
			containersEditTab.addTab('text_container', query('#btn_project_text').click(function() { 
				containersEditTab.changeTab('text_container'); 
				return false;
			}), 
			query('.tab_project_text'));
			
			containersEditTab.addTab('embed_container', query('#btn_project_embed').click(function() { 
				containersEditTab.changeTab('embed_container'); 
				return false;
			}), 
			query('.tab_project_embed'));

			containersEditTab.addTab('photo_container', query('#btn_project_photo').click(function() { 
				containersEditTab.changeTab('photo_container'); 
				return false;
			}), 
			query('.tab_project_photo'));
			
			containersEditTab.changeTab('text_container');
		}
	}
})

.module('project_container_request', function(context) {

	var util = context.util,
		query = context.query,
		require = context.require,
		notify = require('notify'),
		
		project_id,
		processing = false;

	return {
		
		init: function(settings) {
			project_id = settings.id;
		},

		events: {
			
			saveProjectElement: function(data, callback) {
				
				if(processing) {
					return;
				}

				processing = true;
				var request_data = util.extend(data, { id: project_id});

				context.request({	
					
					url: '/project/add_container',
					dataType: 'json',
					type: "post",
					data: request_data,
					
					success: function(data) {
						
						if(data.success === true) {
							callback && callback.call(null, data);

							notify.create("create", {
                        		title: data.message,
                       		 	text: data.description
                    		});

						} else {
							
							var err_msg = '';
						
							util.eachRecursive(data.errors, function(key, val) {
								err_msg += err_msg === '' ? val : '<br/>' + val;
							});
							
							notify.create('create','error-template', {
								title: data.message,
								text: err_msg
							});
						}
					},

					error: function(err) {
						console.log('add project container error: ' + err);

						notify.create('create','error-template', {
							title: 'Error',
							text: 'Project element <b>' + request_data.title + '</b> cannot be added. Service unavailable.'
						});
					},

					complete: function() {
						processing = false;
					}
				});
			}
		}
	}
})

.module('container_text', function(context) {
	
	var query = context.query,
		require = context.require,
		notify = require('notify'),

		container_text_value,
		btn_add,

		onAddHandler = function() {
			
			if(container_text_value.val().length > 0) {

				var request_data = {
					type: 'TEXT',
					data: {
						text: container_text_value.val()
					}
				}
				
				context.trigger('saveProjectElement', request_data, onContainerAdded);
			
			} else {

				notify.create('create','error-template', {
					title: 'Cannot add project element',
					text: 'Element must not be empty.'
				});
			}
		},

		onContainerAdded = function(data) {
			context.trigger('addProjectElement', data.content);
			container_text_value.val('');
		};

	return {
		
		init: function(settings) {
			container_text_value = query('#container_text_value'); 
			btn_add = query('#btn_add_text_container');
			btn_add.bind('click',onAddHandler);
		},
		
		destroy: function() {
			btn_add.unbind('click');
		}
	}
})

.module('container_photo', function(context) {
	
	var fileUploader = context.require('FileUploader'),
		photoUploader,
		query = context.query,
		btn_upload_project_photo,

		onUploadCompleteHandler = function(id, fileName, data) {
			if(data.success === true) {
				context.trigger('addProjectElement', data.content);
			}
		};

	return {
		
		init: function(settings) {
			btn_upload_project_photo = query('#project_photo');

			var request_data = {
					id: settings.id, 						// project_id
					type: 'PHOTO',
			};

			photoUploader = fileUploader.create({
				element: btn_upload_project_photo.get(0),
				action: '/project/add_container',
	            name: 'project_photo',
	            params: request_data,
	            allowedExtensions: ['png','jpg','jpeg'],   
		        sizeLimit: 2*1024*1024,
				multiple: true,
				onComplete: onUploadCompleteHandler
			});
		}
	}
})

.module('container_embed', function(context) {
	
	var query = context.query,
		require = context.require,
		notify = require('notify'),
		
		container_embed_value,
		container_embed_preview,
		container_embed_preview_action,
		btn_add,

		processing = false,
		currentLink = '',
		responseData = null,

		onPasteLinkHandler = function() {

			// deffer to the next tick loop (value on paste event not being populated yet)
			setTimeout(function() {
				if(currentLink !== container_text_value.val() && container_text_value.val() !== '') {
					currentLink = container_text_value.val();

					var request_data = {
						page: currentLink
					}

					// get info view
					context.request({	
						
						url: '/project/get_embed_info',
						dataType: 'json',
						type: "post",
						data: request_data,
						
						success: function(data) {
							
							if(data.success === true) {
								
								responseData = data.url;
								container_embed_preview.html(data.content).show();
								container_embed_preview_action.show();

							} else {
								
							}
						},

						error: function(err) {
							console.log('add project container error: ' + err);
							
							notify.create('create','error-template', {
								title: 'Cannot display info',
								text: 'Project element <b>' + request_data.title + '</b> cannot display info. Service unavailable.'
							});
						},

						complete: function() {
							processing = false;
						}
					});
				}
			}, 0);
		},

		onAddHandler = function() {

			if(responseData !== null && responseData !== undefined) {

				var request_data = {
					type: 'EMBED',
					data: {
						url: responseData 
					}
				}
				
				context.trigger('saveProjectElement', request_data, onContainerAdded);
			
			} else {

				notify.create('create','error-template', {
					title: 'Cannot add project element',
					text: 'Element must not be empty.'
				});
			}
		},

		onContainerAdded = function(data) {
			context.trigger('addProjectElement', data.content);
			responseData = null;
			currentLink = '';

			container_text_value.val('');
			container_embed_preview.html('').hide();
			container_embed_preview_action.hide();
		};

	return {
		
		init: function(settings) {
			container_text_value = query('#container_embed_value'); 
			container_embed_preview = query('#container_embed_preview').hide();
			btn_add = query('#btn_add_embed_container');
			container_embed_preview_action = query('#container_embed_preview_action').hide();

			container_text_value.bind('paste change', onPasteLinkHandler)
			btn_add.bind('click',onAddHandler);
		},
		
		destroy: function() {
			btn_add.unbind('click');
			container_text_value.unbind('paste change');
		}
	}
})

// Main image thumbnail select
// **************************************************************************************************

.module('thumbnail_select', function(context) {
	var $ = query = context.query,
		request = context.request,
		jCrop = context.require('jCrop'),
		
		content,
		container,
		selectedContainer,
		img_box,
		img,
		img_w,
		img_h,
		img_thumb,
		thumbnail_manipulation,
		btn_thumb_create,
		btn_thumb_cancel,

		jCropApi,

		project_miniature,
		project_id,

		thumb = {},
		processing = false,
		ajax_loader;

	function onThumbSelect(coords) {
		var rx = 210 / coords.w;
		var ry = 160 / coords.h;

		util.extend(thumb, coords);

		img_thumb.css({
			width: Math.round(rx * img_w) + 'px',
			height: Math.round(ry * img_h) + 'px',
			marginLeft: '-' + Math.round(rx * coords.x) + 'px',
			marginTop: '-' + Math.round(ry * coords.y) + 'px'
		});
	} 

	function onThumbnailAccept() {
		
		if(selectedContainer && selectedContainer.length > 0 && processing === false) {

			var request_data = util.extend({
				project_id: project_id,
				image_url: img.src
			}, thumb);

			clearThumbnail();
			ajax_loader.fadeIn('slow');

			request({	
				
				url: '/project/create_thumbnail',
				dataType: 'json',
				type: "post",
				data: request_data,

				success: function(data) {
					if(data.success === true) {
						project_miniature.find('p').hide(); 
						project_miniature.find('img').remove();

						var delete_btn = project_miniature.find('#delete_thumbnail');
						if(delete_btn.length === 0) {
							$('<a href="/project/delete_thumbnail" id="delete_thumbnail" class="delete_photo">x</a>').appendTo(project_miniature);
						} else {
							delete_btn.css('display', 'block');
						}

						var proj_img_thumb = $('<img/>').appendTo(project_miniature);
						proj_img_thumb
						.attr('src', data.thumbnail_path)
						.hide()
						.fadeIn('slow');
					}
				},

				error: function(err) {
					notify.create('create','error-template', {
						title: 'Error',
						text: 'Cannot save layout. Service unavailable.'
					});
				},

				complete: function() {
					processing = false;
					ajax_loader.hide();
				}
			});
		}
	}

	function onThumbnailCancel() {
		clearThumbnail();
	}

	function createThumbnail() {
		
		clearThumbnail();

		selectedContainer = $(this).parents('.image_container');

		img_box = selectedContainer.find('.image_box');
		img = img_box.find('img')[0];										// big image
		thumbnail_manipulation = img_box.find('.thumbnail_manipulation');
		img_thumb = thumbnail_manipulation.find('img');

		btn_thumb_create = thumbnail_manipulation.find('#thumbnail_create');
		btn_thumb_cancel = thumbnail_manipulation.find('#thumbnail_cancel');

		btn_thumb_create.bind('click', onThumbnailAccept);
		btn_thumb_cancel.bind('click', onThumbnailCancel);

		img_w = img.width;
		img_h = img.height;img
		img_box.css('width', img_w);
		thumbnail_manipulation.show();

		jCrop.create(img, {
			onSelect:    onThumbSelect,
			onChange:    onThumbSelect,
            bgColor:     'black',
            bgOpacity:   .4,
            setSelect:   [ 0, 0, 210, 160 ],
            aspectRatio: 210 / 160,
            minSize: [210, 160],
            keySupport: false						// issue scroll jumping after focus
        },
        function() {
        	jCropApi = this;
        });

		return false;
	};

	function clearThumbnail() {
		if(selectedContainer && selectedContainer.length > 0) {
			btn_thumb_create.unbind('click', onThumbnailAccept);
			btn_thumb_cancel.unbind('click', onThumbnailCancel);

			thumbnail_manipulation.hide();
			jCropApi.destroy();

			selectedContainer = null;
		}
	}

	function deleteThumbnail(event) {
		var button = $(this),
        	photo =  button.parent().children('img'),
        	action = button.attr('href'),

        	requestData = {
        		id: project_id
        	};
       
        	request({
                url: action,
                dataType: 'json',
                data: requestData,
                type: 'post',

                success: function(data){

                	if(data.success === true) {
                		photo.fadeOut(1000, function(){ 
                    		photo.remove();
                    		project_miniature.find('p').fadeIn('fast'); 
                    	});
                    	
                    	button.css('display','none');
                	}
                }
        	});

        event.preventDefault();
    }

	return {
		init: function(settings) {
			project_id = settings.id;

			ajax_loader = query('#ajax_loader');
			container = query('.project_list', '#project_content');
			content = query('#content');

			content.on('click', '#delete_thumbnail', deleteThumbnail);
			container.on('click', '.btn_thumbnail', createThumbnail);
			project_miniature = query('#project_miniature'); 
		},

		destroy: function() {
			container.off('click', '.btn_thumbnail', createThumbnail);
			content.off('click', '#delete_thumbnail', deleteThumbnail);
		}
	}
})

// Publish project
// **************************************************************************************************

.module('publish_project', function(context) {
	var query = context.query,
		request = context.request,
		require = context.require,
		notify = require('notify'),

		project_id,
		btn_publish,
		ajax_loader,
		processing = false;
		published = true;


	context.bind('addProjectElement', function() {
		published = false;
		btn_publish.show();
	});
		
	function publishChanges() {

		if(published === true || processing === true) {
			return false;
		}
		
		var request_data = {
			project_id: project_id
		};

		ajax_loader.fadeIn('slow');

		request({	
			
			url: '/project/publish_updates',
			dataType: 'json',
			type: "post",
			data: request_data,

			success: function(data) {
				if(data && data.success === true) {
					btn_publish.hide();

					notify.create("create", {
                    	title: data.message,
                        text: data.description
                    });

					query('.unpublished .image_box > img, .unpublished .image_box > .jcrop-holder, .unpublished iframe, .unpublished .text_box')
					.animate({opacity: 1}, 600, function() {
						$(this).parents('.unpublished').removeClass('unpublished');
					});
				}
			},

			error: function(err) {
				notify.create('create','error-template', {
					title: 'Error',
					text: 'Project cannot be published. Service unavailable.'
				});
			},

			complete: function() {
				processing = false;
				ajax_loader.hide();
			}
		});	
		
		return false;
	}

	return {
		init: function(settings) {
			project_id = settings.id;
			published = query('.unpublished').length === 0;
			ajax_loader = query('#ajax_loader'); 
			btn_publish = query('#btn_publish');
			btn_publish.bind('click', publishChanges);
		},

		destroy: function() {
			btn_publish.unbind('click', publishChanges);
		}
	}
})

// Action delete (containers)
// **************************************************************************************************

.module('actionDelete', function(context) {
	var query = $ = context.query,
		require = context.require,
		request = context.request,
		notify = require('notify'),
		actionDeleteDialog = require('actionDialog');

	return {
		init: function() {
			
			actionDeleteDialog.create('.delete', function(el) {
		        
		        var anchor = el,
		        	action = anchor.attr('href');
		        
		        request({
		            url: action,
		            dataType: 'json',
		            success: function(data) {
		            	anchor.parents('li').slideUp('fast', function() {
		            		$(this).remove();	
		            	})
		            },

		            error: function() {
		            	notify.create('create','error-template', {
							title: 'Error',
							text: 'Cannot remove element. Service unavailable.'
						});
		            }
		        });
		    });   
		}
	}
})

// Tooltips (containers)
// **************************************************************************************************

.module('tooltips', function(context) {
	var query = context.query,
		require = context.require,
		tipsy = require('tipsy');

	return {
		init: function() {
			tipsy.init('.tooltip', {gravity: 'se'});
		}
	}
})


 